from Tkinter import *
import ProjectWizard
import tkMessageBox
import tkFileDialog
import Document
import string
import webbrowser
#import ProjectTester
from datetime import datetime

class MainFrame():
    
    def __init__(self, controller, projectTester=None):

        self.controller = controller
        self.projectTester = projectTester
        
        #Main setup
        self.master = Tk()
        self.master.title("Anonymouth: Anti-Stylometry")
        master = self.master
        
        frame = Frame(master)
        frame.grid(row=0, column=0, sticky=E+W+S+N)
        self.frame = frame
        
        master.rowconfigure(0, weight=1)
        master.columnconfigure(0, weight=1)
        master.minsize(800,400)
        #frame.pack()
        
        self.clipboard = ""

        self.documentMatch = StringVar()
        self.tempDocumentMatch = StringVar()
        
        #Text area setup
        self.setupTextArea(frame)
        self.setupMatchArea(frame)
        
        #Menubar setup
        menubar = Menu(self.master)

        #File menu
        self.setupFileMenu(menubar)
        
        #Edit menu
        self.setupEditMenu(menubar, frame)
        
        #Tools menu
        self.setupToolsMenu(menubar, frame)
        
        #Window menu
        self.setupWindowMenu(menubar, frame)
        
        #Help menu
        self.setupHelpMenu(menubar, frame)
        
        #Add menu to frame
        self.master.config(menu=menubar)

        #Train button
        self.trainButton = Button(frame, text="TRAIN",fg="red",comman=self.trainCorpus)
        self.trainButton.grid(row=3,column=2)
        #Submit button
        self.submitButton = Button(frame, text="SUBMIT", fg="red", command=self.submitProject)
        self.submitButton.grid(row=4, column=2)
        
        #Suggestions and Revisions boxes
        self.setupSuggestionsArea(frame)
        self.setupRevisionsArea(frame)
        
        frame.rowconfigure(0, weight=1)
        frame.rowconfigure(1, weight=1)
        frame.rowconfigure(2, weight=1)
        frame.rowconfigure(3, weight=1)
        frame.rowconfigure(4, weight=1)
        frame.rowconfigure(5, weight=1)
        frame.rowconfigure(6, weight=1)
        frame.rowconfigure(7, weight=1)
        frame.columnconfigure(0, weight=8)
        #frame.columnconfigure(1, weight=1)
        frame.columnconfigure(2, weight=1)
        #frame.columnconfigure(3, weight=1)
        frame.columnconfigure(4, weight=1)
        #frame.columnconfigure(5, weight=1)
        
        #Suggestions holder
        #self.allSuggestions = []
        self.allSuggestions = dict()
        
        #Listeners
        self.frame.bind_all("<Control-f>", self.openFindShortcut)
        self.frame.bind_all("<Escape>", self.resetStyles)

    def start(self):
        if self.projectTester!=None:
            self.projectTester.start()
        self.master.mainloop()        

    def setupTextArea(self, frame):
        self.text_area = Text(frame, background='white', undo=1, height=25, width=60, wrap='word')
        self.text_area.grid(row=0, column=0, rowspan=6, sticky=E+W+S+N)
        self.text_areaScroll = Scrollbar(frame, orient=VERTICAL, command=self.text_area.yview)
        self.text_area['yscrollcommand']=self.text_areaScroll.set
        self.text_areaScroll.grid(row=0, rowspan=6, column=1, sticky=N+S)
        
    def setupMatchArea(self, frame):
        self.matchFrame = LabelFrame(frame, relief=RIDGE, text='Author Identification Percentage')
        self.matchFrame.grid(row=7, column=0, sticky=E+W+S+N)
        self.matchFrame.rowconfigure(0, weight=1)
        self.matchFrame.columnconfigure(0, weight=1)
        self.matchFrame.columnconfigure(1, weight=1)
        self.styloMatch = LabelFrame(self.matchFrame, relief=SUNKEN, text='Most Recent Author Match Percentage')
        self.styloMatch.grid(row=0, column=0, sticky=E+W+S+N)

        self.currentMatch = LabelFrame(self.matchFrame, relief=SUNKEN, text='Best Estimate Author Match Percentage')
        self.currentMatch.grid(row=0, column=1, sticky=E+W+S+N)        

        self.styloMatchValue = Label(self.styloMatch, textvariable=self.documentMatch)
        self.styloMatchValue.grid(row=0, column=0, sticky=S+N)
        self.styloMatch.rowconfigure(0, weight=1)
        self.styloMatch.columnconfigure(0, weight=1)
        self.documentMatch.set('')
        

        
        self.currentMatchValue = Label(self.currentMatch, textvariable=self.tempDocumentMatch)
        self.currentMatchValue.grid(row=0, column=0, sticky=E+W+S+N)
        self.currentMatch.rowconfigure(0, weight=1)
        self.currentMatch.columnconfigure(0, weight=1)
        self.tempDocumentMatch.set('')
        
    def setupFileMenu(self, menubar):
        filemenu = Menu(menubar, tearoff=0)
        filemenu.add_command(label="New Project", command=self.newProject)
        filemenu.add_command(label="Open", command=self.openProject)
        filemenu.add_command(label="Save", command=self.saveProject)
        filemenu.add_command(label="Save As...", command=self.saveProjectAs)
        #recentmenu = Menu(filemenu, tearoff=0)
        #recentmenu.add_command(label="etc", command=self.func2)
        #filemenu.add_cascade(label="Recent Projects", menu=recentmenu)
        #filemenu.add_command(label="Close Project", command=self.func2)
        filemenu.add_separator()
        #filemenu.add_command(label="Export Project", command=self.func2)
        filemenu.add_separator()
        #filemenu.add_command(label="Print...", command=self.func2)
        filemenu.add_separator()
        filemenu.add_command(label="Quit", command=self.master.quit)
        menubar.add_cascade(label="File", menu=filemenu)
        
    def setupEditMenu(self, menubar, frame):
        editmenu = Menu(menubar, tearoff=0)
        editUndo = lambda: self.text_area.edit_undo()
        editmenu.add_command(label="Undo (Ctrl-Z)", command=editUndo)
        editRedo = lambda: self.text_area.edit_redo()
        editmenu.add_command(label="Redo (Ctrl-Y)", command=editRedo)
        
        editCut = lambda: self.cut(self.text_area)
        editmenu.add_command(label="Cut (Ctrl-X)", command=editCut)
        editCopy = lambda: self.copy(self.text_area)
        editmenu.add_command(label="Copy (Ctrl-C)", command=editCopy)
        editPaste = lambda: self.paste(self.text_area)
        editmenu.add_command(label="Paste (Ctrl-V)", command=editPaste)
        editmenu.add_separator()
        
        openFindWindow = lambda: self.openFindWindow(frame)
        editmenu.add_command(label="Find/Replace", command=openFindWindow)
        menubar.add_cascade(label="Edit", menu=editmenu)
        
    def setupToolsMenu(self, menubar, frame):
        toolsmenu = Menu(menubar, tearoff=0)
        openCorpusWindow = lambda: self.openCorpusWindow(frame)
        toolsmenu.add_command(label="Manage Corpus", command=openCorpusWindow)
        #presetmenu = Menu(toolsmenu, tearoff=0)
        #presetmenu.add_command(label="etc", command=self.func2)
        #toolsmenu.add_cascade(label="Preset Corpus", menu=presetmenu)
        menubar.add_cascade(label="Tools", menu=toolsmenu)
        
    def setupWindowMenu(self, menubar, frame):
        windowmenu = Menu(menubar, tearoff=0)
        #Stuff
        menubar.add_cascade(label="Window", menu=windowmenu)
        
        
    def setupHelpMenu(self, menubar, frame):
        helpmenu = Menu(menubar, tearoff=0)
        helpmenu.add_command(label="Everything about Anonymouth", command=self.tutorialPage)
        #helpmenu.add_command(label="Contents", command=self.func2)
        helpmenu.add_separator()
        #helpmenu.add_command(label="About", command=self.func2)
        menubar.add_cascade(label="Help", menu=helpmenu)
        
    def tutorialPage(self):
        webbrowser.open_new('http://code.google.com/p/anonymouth/wiki/')
        
    def setupSuggestionsArea(self, frame):
        self.suggestionArea=Listbox(frame, font=("size=16,underline=0"),bg="#d4d0c8",selectbackground="#777777",activestyle="dotbox",width=25)
        self.showFeatureOptions(self.suggestionArea)
        self.suggestionArea.grid(row=0, column=2, sticky=E+W+N+S)
        self.suggestionScroll = Scrollbar(frame, orient=VERTICAL, command=self.suggestionArea.yview)
        self.suggestionArea['yscrollcommand']=self.suggestionScroll.set
        self.suggestionScroll.grid(row=0, rowspan=1, column=3, sticky=N+S)
        #self.suggestionArea.bind("<Double-Button-1>", lambda e: self.suggestionAreaFind(self.suggestionArea,e))
        self.suggestionArea.bind("<Double-Button-1>", lambda e: self.handleDoubleClick(self.suggestionArea,e))
        
    def addSuggestions(self, featureSuggestions):
        
        '''For each featureSuggestion in the list
            Get the feature from the FeatureSuggestions class
            Get all of its suggestions
                For each of the suggestions
                    Add a new item to the list with the background color as feature.getColor. The text will be black'''
        if self.suggestionArea.size() > 0:
            self.suggestionArea.delete(0, self.suggestionArea.size() - 1)
        
		#self.allSuggestions = []
        suggestions = []
        '''
        Features for this look like this:
            Dictionary:
            'Wordcount': {Suggestion1, Suggestion2}
            'AvgWhatever': {Suggestion1, Suggestion2, SuggestionN}
        '''
        lastSuggestionType = ''
  
        allSuggestions = []
        usedSuggestions = []

        for feature in range(len(featureSuggestions)):
            suggestionList = featureSuggestions[feature].getSuggestions()
            suggestionList = list(set(suggestionList))
            #print 'SuggestionList'
            #print suggestionList
            for suggestion in range(len(suggestionList)):
                if lastSuggestionType == '':
                        lastSuggestionType = suggestionList[suggestion].getHelpText()
                
                if lastSuggestionType != suggestionList[suggestion].getHelpText() or feature == len(featureSuggestions) - 1:
                    self.allSuggestions[lastSuggestionType] = allSuggestions
                    
                    self.suggestionArea.insert(END, lastSuggestionType)
                    allSuggestions = []
            #allSuggestions.append(suggestionList[suggestion])

                allSuggestions.append(suggestionList[suggestion])
				#self.allSuggestions.append(suggestionList[suggestion])
                #suggestionColor = suggestionList[suggestion].getColor()
                #self.suggestionArea.insert(END, suggestionList[suggestion].getHelpText() + ' - ' + suggestionList[suggestion].getOriginalText())
                '''Can't get background to work right now'''
                '''self.suggestionArea().itemconfigure(j, option=suggestionColor)'''
            
            lastSuggestionType = suggestionList[suggestion].getHelpText()
       # print self.allSuggestions
                
        
        
    def setupRevisionsArea(self, frame):
        self.revisionArea=Listbox(frame, font=("size=16,underline=0"),bg="#d4d0c8",selectbackground="#777777",activestyle="dotbox",width=25)
        self.revisionArea.bind("<Double-Button-1>", self.revisionsArea_click)
        self.revisionArea.grid(row=0, column=4, sticky=E+W+N+S)
        self.revisionScroll = Scrollbar(frame, orient=VERTICAL, command=self.revisionArea.yview)
        self.revisionArea['yscrollcommand']=self.revisionScroll.set
        self.revisionScroll.grid(row=0, rowspan=1, column=5, sticky=N+S)
    
    def showFeatureOptions(self, suggestionArea):
        if (suggestionArea.tk.call('tk', 'windowingsystem')=='aqua'):
            suggestionArea.bind('<2>', lambda e: self.suggestionAreaCallback(suggestionArea,e))
            suggestionArea.bind('<Control-1>', lambda e: self.suggestionAreaCallback(suggestionArea,e))
        
        else:
            suggestionArea.bind('<3>', lambda e: self.suggestionAreaCallback(suggestionArea,e))
                
    def handleDoubleClick(self, suggestionArea, e):
        selection = suggestionArea.curselection()
        if len(selection) == 1:
            defaultClickedOnSuggestion = 'suggestion'
            self.selectedListBox = suggestionArea.get(selection)
            if self.allSuggestions.get(self.selectedListBox, defaultClickedOnSuggestion) == defaultClickedOnSuggestion:
                self.suggestionAreaFind(suggestionArea)
            else:
                self.openFeatureIndex = int(suggestionArea.curselection()[0])
                self.hideAll(suggestionArea)
                self.openFeatureIndex = int(suggestionArea.curselection()[0])
                self.openSuggestionList(suggestionArea)
				
	#Screw you, law of Demeter! I have deadlines!
    #def suggestionAreaFind(self, suggestionArea, e):
    def suggestionAreaFind(self, suggestionArea):
        #if len(suggestionArea.curselection()) == 1:
        #suggestionIndex = int(suggestionArea.curselection()[0])
        suggestionIndex = int(suggestionArea.curselection()[0])
        #suggestion = self.allSuggestions[suggestionIndex]
        suggestionNumber = suggestionIndex - self.openFeatureIndex - 1
        suggestions = self.allSuggestions[suggestionArea.get(self.openFeatureIndex)]
        suggestion = suggestions[suggestionNumber]
        self.find(self.text_area, suggestion.originalText, suggestion.color)
		
    def hideAll(self, suggestionArea):
        i = 0
        suggestionAreaSize = suggestionArea.size()
        while i < suggestionAreaSize:
            suggestionText = suggestionArea.get(i)
            if string.find(suggestionText, '--- ') != -1:
                suggestionArea.delete(i)
                suggestionAreaSize = suggestionAreaSize - 1
                continue
            i = i + 1
		
    def openSuggestionList(self, suggestionArea):
        suggestionIndex = int(suggestionArea.curselection()[0])
        suggestions = self.allSuggestions[self.selectedListBox]
        for i in range(len(suggestions)):
            self.suggestionArea.insert(self.openFeatureIndex + 1 + i, '--- ' + str(i) + '. '+ suggestions[i].getHelpText() + ' - ' + suggestions[i].getOriginalText())
                
    def suggestionAreaCallback(self, suggestionArea, e):
        selection = suggestionArea.curselection()
        if len(selection) == 1:
            defaultClickedOnSuggestion = 'suggestion'
            self.selectedListBox = suggestionArea.get(selection)
            if self.allSuggestions.get(self.selectedListBox, defaultClickedOnSuggestion) == defaultClickedOnSuggestion:
                suggestionIndex = int(suggestionArea.curselection()[0])
                #suggestion = self.allSuggestions[suggestionIndex]
               
                suggestions = self.allSuggestions[suggestionArea.get(self.openFeatureIndex)]
                suggestionNumber = suggestionIndex - self.openFeatureIndex - 1
                suggestion = suggestions[suggestionNumber]
				
                suggestionMenu = Menu(suggestionArea, tearoff=0)
                suggestionMenu.add_command(label=suggestion.suggestionText)
                suggestionMenu.entryconfig(0,state=DISABLED)
                suggestionMenu.add_separator()
                replaceSuggestion = lambda: self.replaceSuggestion(suggestionIndex, suggestionArea)
                suggestionMenu.add_command(label="Replace", command=replaceSuggestion)
                compareSuggestion = lambda: self.compareSuggestion(suggestionIndex, suggestionArea)
                suggestionMenu.add_command(label="Compare", command=compareSuggestion)
                ignoreSuggestion = lambda: self.ignoreSuggestion(suggestionIndex, suggestionArea)
                suggestionMenu.add_command(label="Ignore", command=ignoreSuggestion)
                suggestionMenu.post(e.x_root, e.y_root)
            
    def compareSuggestion(self, suggestionIndex, suggestionArea):
        suggestionIndex = int(suggestionArea.curselection()[0])
        suggestions = self.allSuggestions[suggestionArea.get(self.openFeatureIndex)]
        suggestionNumber = suggestionIndex - self.openFeatureIndex - 1
        suggestion = suggestions[suggestionNumber]
        
        #Backup text area and then call the function to submit document without changing the suggestion area
        tempTextArea = self.text_area
        tempTextArea.delete(self.pos, self.posend)
        #tempTextArea.insert(self.pos, self.allSuggestions[suggestionIndex].suggestionText)
        tempTextArea.insert(self.pos, suggestion.suggestionText)
        self.controller.submit(Document.Document(self.text_area),'Null', False)
        match = str(self.controller.setCurrentMatch()) + '%'
        author = str(self.controller.setCurrentAuthor())
        self.tempDocumentMatch.set('Author1 ' + author + ' ' + match)
           
    def replaceSuggestion(self, suggestionIndex, suggestionArea):
        '''Go through the text area and find the first occurence of the original text.
        At this position, replace it with the replacement text'''
        
        suggestionIndex = int(suggestionArea.curselection()[0])
        suggestions = self.allSuggestions[suggestionArea.get(self.openFeatureIndex)]
        suggestionNumber = suggestionIndex - self.openFeatureIndex - 1
        suggestion = suggestions[suggestionNumber]
        
        self.text_area.delete(self.pos, self.posend)
        self.text_area.insert(self.pos, suggestion.suggestionText)
        self.suggestionArea.delete(suggestionIndex)
        del suggestions[suggestionNumber]
    
    def ignoreSuggestion(self, suggestionIndex, suggestionArea):
        self.suggestionArea.selection_clear(suggestionIndex)
        suggestions = self.allSuggestions[suggestionArea.get(self.openFeatureIndex)]
        suggestionNumber = suggestionIndex - self.openFeatureIndex - 1
        suggestion = suggestions[suggestionNumber]
        self.suggestionArea.delete(suggestionIndex)
        del suggestions[suggestionNumber]
        
    def copy(self, textarea):
        textarea.clipboard_append(textarea.selection_get())
        
    def cut(self, textarea):
        textarea.clipboard_append(textarea.selection_get())
        textarea.delete("sel.first", "sel.last")
        
    def paste(self, textarea):
        text = textarea.selection_get(selection='CLIPBOARD', type='STRING')
        textarea.insert("insert", text)
        #textarea.insert( textarea.clipboard )
        
    def openFindWindow(self,frame):
        #Search window
        swindow = Toplevel(frame)
        swindow.title("Find/Replace")
        swindow.geometry('400x200-5+40')
        #FOR COOLNESS swindow.attributes("-alpha",0.5)
        #swindow = Frame(swindow)
        swindow.searchLabel = Label(swindow, text="Find: ")
        swindow.searchLabel.grid(row=0,column=0, pady=10, padx=5, columnspan=2, sticky=E)
        swindow.searchText = Entry(swindow)
        swindow.searchText.grid(row=0, column=2, pady=10, padx=2, columnspan=2)
        find = lambda: self.find(self.text_area, swindow.searchText.get())
        swindow.searchButton = Button(swindow, text="Find", command=find, width=10)
        swindow.searchButton.grid(row=0,column=4, pady=10, padx=30, columnspan=2, sticky=W)
        swindow.replaceLabel = Label(swindow, text="Replace: ")
        swindow.replaceLabel.grid(row=1,column=0, pady=10, padx=5, columnspan=2, sticky=E)
        swindow.replaceText = Entry(swindow)
        swindow.replaceText.grid(row=1, column=2, pady=10, padx=2, columnspan=2)
        replace = lambda: self.replace()
        swindow.replaceButton = Button(swindow, text="Find/Replace", command=replace, width=10)
        swindow.replaceButton.grid(row=1,column=4, pady=10, padx=30, columnspan=2, sticky=W)
        swindow.bind("<Destroy>", self.clearFind)
        swindow.focus_set()
        
    def find(self, text_area, findtext, color):
        text_area.tag_delete("search")
        reg_exp = findtext
        #print reg_exp
        self.pos = text_area.search(findtext,1.0,forwards=1, regexp=reg_exp, stopindex=END)
        #while pos:
            #posend = (float(pos)/10.0+float(len(findtext))/100.0)*10.0
        self.posend = '%s+%dc' % (self.pos, len(findtext))
        #print self.posend
        text_area.mark_set("searchMatchStart",self.pos)
        text_area.mark_set("searchMatchEnd",self.posend)
        text_area.tag_config("search", background=color)
        text_area.tag_add("search", "searchMatchStart","searchMatchEnd")
        #pos = text_area.search(findtext,posend, regexp=reg_exp, forwards=1, stopindex=END)
        
    
    def clearFind(self, event):
        text_area = self.text_area
        text_area.tag_delete("search")
        
    def resetStyles(self, event):
        self.clearFind(event)
        
    def openFindShortcut(self, event):
        self.openFindWindow(self.frame)
                
    #Should probably be in a seperate class
    def openCorpusWindow(self, frame):
        #corpus window
        swindow = Toplevel(frame)
        swindow.title("Corpus Manager")
        swindow.geometry('400x400-5+40')
        swindow.searchLabel = Label(swindow, text="Corpus: ")
        swindow.searchLabel.grid(row=0,column=0, pady=10, padx=5, columnspan=2)
        
        swindow.corpusArea=Listbox(swindow, activestyle="dotbox",width=35)
        swindow.corpusArea.grid(row=1,column=0,pady=5,padx=10,rowspan=3,sticky=E)
        
        self.scrollY = Scrollbar(swindow, orient=VERTICAL, command=swindow.corpusArea.yview, width=35)
        self.scrollY.grid(row=1, column=0, padx=10, pady=5, rowspan=3, sticky=N+E)
        
        swindow.corpusArea["yscrollcommand"] = self.scrollY.set
        
        removeFolder = lambda: self.removeFolderFromCorpus(swindow.corpusArea)
        swindow.removeButton = Button(swindow, text="Remove Author", command=removeFolder, width=15)
        addFolder = lambda: self.addFolderToCorpus(swindow.corpusArea)
        swindow.removeButton.grid(row=1,column=1, pady=10, padx=10, sticky=E)
        swindow.addButton = Button(swindow, text="Add Author", command=addFolder, width=15)
        swindow.addButton.grid(row=2,column=1, pady=10, padx=10, sticky=E)
        '''editDocument = lambda: self.editDocument(swindow.corpusArea)
        swindow.editButton = Button(swindow, text="Edit Document Path", command=editDocument, width=15)
        swindow.editButton.grid(row=3,column=1, pady=10, padx=10, sticky=W)'''

        swindow.bottomButtonFrame = Frame(swindow)
        swindow.bottomButtonFrame.grid(row=4, column=0, columnspan=2)

        saveQuitCorpus = lambda: self.saveQuitCorpus(swindow)
        swindow.bottomButtonFrame.okButton = Button(swindow.bottomButtonFrame, text="OK", command=saveQuitCorpus, width=10)
        swindow.bottomButtonFrame.okButton.grid(row=0,column=0, pady=10, padx=10, sticky=E)
        quitCorpus = lambda: swindow.destroy()
        swindow.bottomButtonFrame.cancelButton = Button(swindow.bottomButtonFrame, text="Cancel", command=quitCorpus, width=10)
        swindow.bottomButtonFrame.cancelButton.grid(row=0,column=1, pady=10, padx=10, sticky=E)
        saveCorpus = lambda: self.saveCorpus(swindow.corpusArea)
        swindow.bottomButtonFrame.applyButton = Button(swindow.bottomButtonFrame, text="Apply", command=saveCorpus, width=10)
        swindow.bottomButtonFrame.applyButton.grid(row=0,column=2, pady=10, padx=10, sticky=W)
        
        self.controller.populateListWithCorpusFolders(swindow.corpusArea)
        
        swindow.focus_set()
        
    def removeFolderFromCorpus(self, corpusArea):
        #print ("TEST")
        self.controller.removeCorpusFolder(corpusArea.get(corpusArea.curselection()[0]))
        corpusArea.delete(corpusArea.curselection())

    def addFolderToCorpus(self, corpusArea):
        pathName = tkFileDialog.askdirectory()
        if not pathName:
            return False
        self.controller.addCorpusFolder(pathName)
        self.controller.populateListWithCorpusFolders(corpusArea)        
    
    def editDocument(self, corpusArea):
        filename = tkFileDialog.askopenfilename(filetypes=[("All files","*"),("Text files","*.txt")])
        corpusArea.insert(corpusArea.curselection(),filename)    
        corpusArea.delete(corpusArea.curselection())
        
    def saveQuitCorpus(self, swindow):
        #swindow.corpusArea
        swindow.destroy()
    
    def trainCorpus(self):
        self.controller.trainCorpus()
    
    def submitProject(self):
        self.addRevision()
        timeStamp = datetime.now()
        '''
        #TESTING: insert the text from f_sample.txt into the text area
        f = open('f_sample.txt', 'r')
        importFileString = f.read()
        self.text_area.insert('1.0', importFileString)
        '''
        self.controller.submit(Document.Document(self.text_area),timeStamp, False)
        match = str(self.controller.setCurrentMatch()) + '%'
        author = str(self.controller.setCurrentAuthor())
        self.documentMatch.set('Author ' + author + ' ' + match)
        self.tempDocumentMatch.set('Author ' + author + ' ' + match)
    
    def newProject(self):
        self.controller.newProject()
            
    def openProject(self):
        self.controller.openProject(self)
        
    def saveProject(self):
        self.controller.saveProject(self,False)
    
    def saveProjectAs(self):
        self.controller.saveProject(self,True)
    
    ''' ----------------------------------------
    Functions relating to RevisionHistory
    '''
            
    def addRevision(self):
        timeStamp = datetime.now()
        document = Document.Document(self.text_area.get(1.0,END))
        self.controller.addRevision(document,timeStamp)
        self.revisionArea.insert(END,timeStamp)
            
            
    def revisionsArea_click(self,unknownVar):
        if tkMessageBox.askyesno(message = 'WARNING: Loading a revision will NOT save changes!', title = 'Revert Document'):
            self.revertToRevision(self.revisionArea.index(ACTIVE))
    
    def revertToRevision(self,revisionIndex):
        revision = self.controller.revertToRevision(revisionIndex)
        self.text_area.delete(1.0,END)
        self.text_area.insert(1.0, revision.getDocument().getText())
        #self.revisionArea.delete(revisionIndex, revisionIndex) KEEP REVISION!!!
    
    '''-----------------------------------------'''
            
    def getController(self):
        return self.controller
    
    def getDocumentText(self):
        return self.text_area.get(1.0,END)
    
    def setTextArea(self,text):
        self.text_area.delete(1.0,END)
        self.text_area.insert(1.0,text)

if __name__ == '__main__': 
    #this runs when you run this file as the main
    
    '''Initializing a controller.'''
    app = MainFrame(None)
    app.start()
